import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutterone/page/me/View/TabListView.dart';
import '../../common/http/global.dart';
import 'ViewModel/meViewModel.dart';
import 'View/TabControl.dart';

class SettingPage extends StatefulWidget {
  SettingPage({Key? key}) : super(key: key);

  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  late Future _loadDataFuture;
  final ScrollController _scrollController = ScrollController();

  int indexSelect = 0;

  @override
  void initState() {
    super.initState();
    _loadDataFuture = getMeData();
    _scrollController.addListener(() {
      double offset = _scrollController.offset;
      double gridSize = MediaQuery.of(context).size.width;
      int currentGridIndex = (offset / gridSize).round();
      double targetOffset = currentGridIndex * gridSize;

      if (indexSelect != currentGridIndex) {
        indexSelect = currentGridIndex;
        _scrollController.animateTo(
          MediaQuery.of(context).size.width * indexSelect,
          duration: const Duration(milliseconds: 150),
          curve: Curves.easeInOut,
        );
      }else if ((offset - targetOffset).abs() > 50) {
        _scrollController.animateTo(
          MediaQuery.of(context).size.width * indexSelect,
          duration: const Duration(milliseconds: 150),
          curve: Curves.easeInOut,
        );
      }
    });
  }

  @override
  void updateIndexSelect(int index) {
    scrollToPosition(MediaQuery.of(context).size.width * index);
  }

  void scrollToPosition(double position) {
    _scrollController.animateTo(
      position,
      duration: const Duration(milliseconds: 150),
      curve: Curves.easeInOut,
    );
  }

  Future<dynamic> getMeData() async {
    try {
      return await Api().getMeData();
    } catch (e) {
      print('Error getting me data: $e');
      return null;
    }
  }

  Future<dynamic> getMePublish() async {
    try {
      return await Api().getMePublish();
    } catch (e) {
      print('Error getting me data: $e');
      return null;
    }
  }

  Future<dynamic> getMeCollect() async {
    try {
      return await Api().getMeCollect();
    } catch (e) {
      print('Error getting me data: $e');
      return null;
    }
  }

  Future<dynamic> getMeLike() async {
    try {
      return await Api().getMeLike();
    } catch (e) {
      print('Error getting me data: $e');
      return null;
    }
  }

  @override
  void dispose() {
    // 释放 ScrollController 资源
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _loadDataFuture,
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return _buildLoading();
        } else if (snapshot.hasError || snapshot.data == null) {
          return _buildError();
        }
        return buildData(snapshot.data);
      },
    );
  }

  Widget _buildLoading() {
    EasyLoading.show(status: '加载中...');
    return Container();
  }

  Widget _buildError() {
    return Container(
      color: Colors.grey,
      child: const Center(child: Text('图片加载失败或暂无图片')),
    );
  }

  Widget buildData(dynamic data) {
    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          SliverAppBar(
            pinned: true,
            floating: false,
            expandedHeight: MediaQuery.of(context).size.height * 0.4 -
                MediaQuery.of(context).padding.top,
            backgroundColor: Colors.orange,
            flexibleSpace: FlexibleSpaceBar(
              background: buildHeadStack(data),
            ),
          ),
          SliverPersistentHeader(
            pinned: true,
            floating: false,
            delegate: MySliverPersistentHeaderDelegate(
                indexSelect, updateIndexSelect),
          ),
        ];
      },
      body: FutureBuilder(
        future: Future.wait([getMePublish(), getMeCollect(), getMeLike()]),
        builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            EasyLoading.show(status: '加载中...');
            return const Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            EasyLoading.showToast('数据加载出现错误，请稍后再试');
            return const Center(child: Text('数据加载错误'));
          }
          return SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            controller: _scrollController,
            scrollDirection: Axis.horizontal,
            child: Row(
              children: [
                for (int i = 0; i < 3; i++)
                  if (snapshot.data![i].length > 0)
                    Container(
                      margin: const EdgeInsets.all(10),
                      width: MediaQuery.of(context).size.width - 20,
                      height: MediaQuery.of(context).size.height,
                      child: CreatMeListView(data: snapshot.data![i]['list']),
                    ),
              ],
            ),
          );
        },
      ),
    );
  }

  Stack buildHeadStack(data) {
    return Stack(
      children: [
        buildFadeInImage(data['person']),
        buildPositioned(),
        buildPadding(data['person']),
      ],
    );
  }

  FadeInImage buildFadeInImage(data) {
    return FadeInImage(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height * 0.4,
      placeholder: const AssetImage('assets/images/testphoto.jpg'),
      image: NetworkImage("$baseImageUrl${data['bgImage']}"),
      fit: BoxFit.cover,
    );
  }

  Positioned buildPositioned() {
    return Positioned(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height * 0.4,
      child: Opacity(
        opacity: 0.3,
        child: Container(color: Colors.grey),
      ),
    );
  }

  Padding buildPadding(data) {
    const TextStyle textStyle = TextStyle(color: Colors.white, fontSize: 14);
    const statusArr = ['关注', '粉丝', '获赞与收藏'];
    var statusNumArr = [data['attention'], data['fans'], data['be_praise']];
    return Padding(
      padding: const EdgeInsets.only(top: 50, left: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Icon(Icons.format_list_bulleted, color: Colors.white, size: 35),
          const SizedBox(height: 30),
          buildTouXiang(data),
          const SizedBox(height: 10),
          buildTextRemark(data),
          buildStatus(statusArr, statusNumArr, textStyle)
        ],
      ),
    );
  }

  Row buildStatus(
      List<String> statusArr, List<dynamic> statusNumArr, TextStyle textStyle) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            for (int i = 0; i < statusArr.length; i++)
              Container(
                padding: const EdgeInsets.all(10),
                child: Column(
                  children: [
                    Text(statusNumArr[i], style: textStyle),
                    const SizedBox(height: 5),
                    Text(statusArr[i], style: textStyle)
                  ],
                ),
              )
          ],
        ),
        Container(
          margin: const EdgeInsets.only(right: 20),
          child: TextButton(
            style: const ButtonStyle(
              side: WidgetStatePropertyAll<BorderSide>(
                BorderSide(
                  color: Colors.white, // 边框颜色
                  width: 1.0, // 边框宽度
                ),
              ),
            ),
            child: const Text("编辑资料",
                style: TextStyle(color: Colors.white, fontSize: 15)),
            onPressed: () async {
              Navigator.pushNamed(context, "/editMeRemark").then((value) {
                setState(() {
                  _loadDataFuture = getMeData();
                });
              });
            },
          ),
        )
      ],
    );
  }

  Padding buildTouXiang(data) {
    return Padding(
      padding: const EdgeInsets.only(left: 20),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(50),
            child: FadeInImage(
              width: 100,
              height: 100,
              placeholder: const AssetImage('assets/images/testphoto.jpg'),
              image: NetworkImage("$baseImageUrl${data['headImg']}"),
              fit: BoxFit.cover,
            ),
          ),
          const SizedBox(width: 15),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(data['name'],
                  style: const TextStyle(
                      color: Colors.white,
                      fontSize: 30,
                      fontWeight: FontWeight.bold)),
              const SizedBox(height: 10),
              Text("账号：${data['tel']}",
                  style: const TextStyle(color: Colors.white, fontSize: 15)),
              Text("地区：${data['area']}",
                  style: const TextStyle(color: Colors.white, fontSize: 15)),
            ],
          ),
        ],
      ),
    );
  }

  TextButton buildTextRemark(data) {
    return TextButton(
      child: Text(data['remark'],
          style: const TextStyle(color: Colors.white, fontSize: 15)),
      onPressed: () async {
        Navigator.pushNamed(context, "/editMeRemark").then((value) {
          setState(() {
            _loadDataFuture = getMeData();
          });
        });
      },
    );
  }
}
